<template>

    <div>
        <el-form :model="form" ref="formEl">
            <el-row :gutter="24">
                <el-col :span="24">
                    <div class="grid-content ep-bg-purple-light" style="padding: 15px 0;">
                        <el-form-item label="简历信息" label-position="top"
                            :style="{ fontSize: '15px', fontWeight: 'bold', borderBottom: '1px dashed #e4e7ed' }">
                            <div class="progress-bar">
                                <div class="progress"></div>
                            </div>
                        </el-form-item>
                    </div>
                </el-col>
            </el-row>

            <!--  -->
            <el-row :gutter="24">
                <el-col :span="8">
                    <div class="grid-content ep-bg-purple-light">
                        <el-form-item label="选择简历" label-position="top" required>
                            <el-button type="primary" style="width: 260px;" @click="JobPopUpWindow"><icon-storage />{{
                                JobData }}</el-button>
                        </el-form-item>
                    </div>
                </el-col>
                <el-col :span="8">
                    <div class="grid-content ep-bg-purple">
                        <el-form-item label="需求编号" label-position="top" required>
                            <el-button type="primary" style="width: 260px;"
                                @click="SelectRequirements"><icon-storage />{{
                                    RequirementID }}</el-button>
                        </el-form-item>
                    </div>
                </el-col>

                <el-col :span="8">
                    <div class="grid-content ep-bg-purple">
                        <el-form-item label="简历编号" label-position="top">
                            <el-input v-model="form.recruitmentDemandNumber" style="width: 260px;" clearable disabled />
                        </el-form-item>
                    </div>
                </el-col>
                <!--  -->

                <el-col :span="8">
                    <div class="grid-content ep-bg-purple-light"><el-form-item label="姓名" label-position="top" required>
                            <el-input v-model="CandidateName" style="width: 260px;" clearable />
                        </el-form-item>
                    </div>
                </el-col>

                <el-col :span="8">
                    <div class="grid-content ep-bg-purple-light"><el-form-item label="手机" label-position="top" required>
                            <div class="el-form-item__content">
                                <el-input v-model="CellPhone" style="width: 260px" clearable />
                            </div>
                        </el-form-item>
                    </div>
                </el-col>
                <el-col :span="8">
                    <div class="grid-content ep-bg-purple-light"><el-form-item label="选择面试官" label-position="top"
                            required>
                            <div class="el-form-item__content">
                                <el-button type="primary" style="width: 260px;" @click="InterviewerButton">{{
                                    InterviewerName }}</el-button>
                            </div>
                        </el-form-item>
                    </div>
                </el-col>
                <!--  -->
                <el-col :span="24">
                    <div class="grid-content ep-bg-purple-light">
                        <el-table :data="ResumeInformation" border
                            :default-sort="{ prop: 'WarehousingDate', order: 'descending' }" style="width: 1400px;">

                            <el-table-column prop="candidateid" label="简历编号" width="160" />
                            <el-table-column prop="dateofresumeaddition" sortable label="入库时间" width="160" />
                            <el-table-column v-for="col in ResumeInformationData" :prop="col.id" :key="col.id"
                                :label="col.label" :width="col.width">
                                <template #default="scope">
                                    <span v-if="col.id === 'gender' && scope.row.gender === 1">女</span>
                                    <span v-else-if="col.id === 'gender' && scope.row.gender === 0">男</span>
                                    <!-- 学历列 -->
                                    <span v-if="col.id === 'degree' && scope.row.degree === 1">本科</span>
                                    <span v-else-if="col.id === 'degree' && scope.row.degree === 0">高中</span>
                                    <span v-else-if="col.id === 'degree' && scope.row.degree === 2">大专</span>
                                    <span v-else-if="col.id === 'degree' && scope.row.degree === 3">研究生</span>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </el-col>
                <!--  -->
                <el-col :span="8">
                    <div class="grid-content ep-bg-purple-light"><el-form-item label="发起时间" label-position="top"
                            required>
                            <el-date-picker v-model="form.theplanbegins" type="datetime" placeholder="选择日期时间"
                                date-format="YYYY/MM/DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
                                style="width: 260px;">
                            </el-date-picker>
                        </el-form-item>
                    </div>
                </el-col>
                <el-col :span="8">
                    <div class="grid-content ep-bg-purple-light"><el-form-item label="结束时间" label-position="top"
                            required>
                            <el-date-picker v-model="form.theProgramEnded" type="datetime" placeholder="选择日期时间"
                                date-format="YYYY/MM/DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
                                style="width: 260px;">
                            </el-date-picker>
                        </el-form-item>
                    </div>
                </el-col>
                <el-col :span="8">
                    <div class="grid-content ep-bg-purple-light"><el-form-item label="面试次数" label-position="top"
                            required>
                            <el-select v-model="form.interviewRound"  style="width: 260px"
                                placement="bottom">
                                <template #label="{ label, value }">
                                    <span style="font-weight: bold">{{ label }}</span>
                                </template>
                                <el-option v-for="item in InterviewRound" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>

                        </el-form-item>
                    </div>
                </el-col>
                
               
            </el-row>
            <div class="form-footer">
                <el-form-item>
                    <el-button type="primary" @click="onSubmit">保存</el-button>
                    <el-button @click="Cancel">取消</el-button>
                </el-form-item>
            </div>
        </el-form>
    </div>
    <!--  -->
    <el-dialog title="选择简历数据" v-model="IntentionDisplay" width="60%" destroy-on-close>

        <el-table :data="IntentionData" border>

            <el-table-column label="选择" width="60" fixed="left">
                <template #default="scope">
                    <el-radio v-model="selectedRowId" :label="scope.row.candidateid">
                        <span class="radio-custom"></span>
                    </el-radio>
                </template>
            </el-table-column>
            <!-- 固定岗位名称列 -->
            <el-table-column prop="candidateid" label="简历编号" width="120" fixed="left" />
            <el-table-column prop="intendedPosition" label="意向岗位" width="120" fixed="left" />
            <el-table-column v-for="col in columns" :prop="col.id" :key="col.id" :label="col.label" :width="col.width">
                <template #default="scope">
                    <span v-if="col.id === 'gender' && scope.row.gender === 1">女</span>
                    <span v-else-if="col.id === 'gender' && scope.row.gender === 0">男</span>
                    <!-- 学历列 -->
                    <span v-if="col.id === 'degree' && scope.row.degree === 1">本科</span>
                    <span v-else-if="col.id === 'degree' && scope.row.degree === 0">高中</span>
                    <span v-else-if="col.id === 'degree' && scope.row.degree === 2">大专</span>
                    <span v-else-if="col.id === 'degree' && scope.row.degree === 3">研究生</span>
                </template>

            </el-table-column>
        </el-table>

        <span>
            <el-button @click="IntentionToCancel">取消</el-button>
            <el-button type="primary" @click="IntentionConfirmed">确认</el-button>
        </span>
    </el-dialog>
    <!--需求弹窗  -->
    <el-dialog title="选择需求数据" v-model="DemandDisplay" width="60%" destroy-on-close>

        <el-table :data="DemandData" border>
            <!-- 单选列 -->
            <el-table-column label="选择" width="60" fixed="left">
                <template #default="scope">
                    <el-radio v-model="SingleChoiceRequirements" :label="scope.row.requirementid">
                        <span class="radio-custom"></span>
                    </el-radio>
                </template>
            </el-table-column>
            <!-- 固定岗位名称列 -->
            <el-table-column prop="requirementid" label="需求编号" width="120" fixed="left" />
            <el-table-column v-for="col in DemandHeader" :prop="col.id" :key="col.id" :label="col.label"
                :width="col.width">
            </el-table-column>
        </el-table>

        <span>
            <el-button @click="IntentionToCancel">取消</el-button>
            <el-button type="primary" @click="DemandDetermination">确认</el-button>
        </span>
    </el-dialog>

    <!--面试官弹窗  -->
    <el-dialog title="选择面试官" v-model="TheInterviewerShows" width="60%" destroy-on-close @open="handleInterviewerDialogOpen">

        <el-table :data="InterviewerData" border ref="interviewerTableRef" @selection-change="handleSelectionChange">
            <el-table-column type="selection" label="选择" width="80" />
            <!-- 固定岗位名称列 -->
            <el-table-column prop="departmentEmployeeNumber" label="编号" width="120" fixed="left" />
            <el-table-column v-for="col in InterviewerInformation" :prop="col.id" :key="col.id" :label="col.label"
                :width="col.width">
            </el-table-column>
        </el-table>

        <span>
            <el-button @click="IntentionToCancel">取消</el-button>
            <el-button type="primary" @click="TheInterviewerIsConfirmed">确认</el-button>
        </span>
    </el-dialog>

</template>

<script setup>
import request from '@/api/request'
import { ref, defineEmits, reactive, nextTick, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { data, param } from 'jquery'

const emit = defineEmits(['ref'])

const interviewerTableRef = ref(null) // 面试官表格引用
const JobData = ref("选择简历数据");//简历数据
const xq = ref("")
const IntentionDisplay = ref(false)

const form = ref({
    recruitmentDemandNumber: '', //需求编号
    interviewRound: '', //面试轮次
})

// 面试时间安排数组
const interviewSchedules = ref([])

// 简历数据弹窗
const JobPopUpWindow = () => {
    console.log(jobname.value);

    if (RequirementID.value && jobname.value) {
        IntentionDisplay.value = true
        request.get('/candidateresume/queryBasedOnTheDemandStatusAndJobName',
            {
                params:
                    { requirements: RequirementID.value, jobName: jobname.value }
            }).then(res => {
                IntentionData.value = res.data
                console.log("简历数据", IntentionData.value);
            })
    } else {
        ElMessage.warning("请选择需求数据")
    }

}

const selectedRowId = ref(null) // 保存当前选中行

const IntentionData = ref([


])// 选择简历数据

const columns = [

    { id: "typeofjobapplication", label: '应聘类型', width: '160' },
    { id: "candidatename", label: '姓名', width: '160' },
    { id: "gender", label: '性别', width: '160' },
    { id: "dateOfBirth", label: '出生年月', width: '160' },
    { id: "age", label: '年龄', width: '160' },
    { id: "degree", label: '学历', width: '160' },
    { id: "specialized", label: '专业', width: '160' },
    { id: "graduationTime", label: '毕业时间', width: '160' },
    { id: "school", label: '毕业院校', width: '160' },
    { id: "marriageAndChildbearing", label: '婚育情况', width: '160' },
    { id: "lastWork", label: '工作经历', width: '160' },
    { id: "resumeStatus", label: '简历状态', width: '160' },
]
// 选择简历数据取消
const IntentionToCancel = () => {
    IntentionDisplay.value = false
}



const ResumeInformationData = ref([

    { id: "intendedPosition", label: '意向岗位', width: '160' },
    { id: "typeofjobapplication", label: '应聘类型', width: '160' },
    { id: "candidatename", label: '姓名', width: '160' },
    { id: "gender", label: '性别', width: '160' },
    { id: "dateOfBirth", label: '出生年月', width: '160' },
    { id: "age", label: '年龄', width: '160' },
    { id: "degree", label: '学历', width: '160' },
    { id: "specialized", label: '专业', width: '160' },
    { id: "graduationTime", label: '毕业时间', width: '160' },
    { id: "school", label: '毕业院校', width: '160' },
    { id: "marriageAndChildbearing", label: '婚育情况', width: '160' },
    { id: "lastWork", label: '工作经历', width: '160' },
    { id: "resumeStatus", label: '简历状态', width: '160' },
]) //简历信息   

const ResumeInformation = ref([]) //简历信息数据

const CandidateName = ref("") //名字
const CellPhone = ref("")//手机号
// 简历岗位确定确定
const IntentionConfirmed = () => {
    const selectedRow = IntentionData.value.find(row => row.candidateid === selectedRowId.value);
    if (selectedRow) {
        console.log('选中的数据:', selectedRow);
        JobData.value = selectedRow.candidateid;
        form.value.recruitmentDemandNumber = selectedRow.candidateid;
        console.log(selectedRow.candidateid);
        CandidateName.value = selectedRow.candidatename;
        CellPhone.value = selectedRow.cellPhone;
        ResumeInformation.value = [selectedRow]; // 将选中的行添加到数组中
        console.log(ResumeInformation.value);
    } else {

        ElMessage.error('未找到匹配的行');
    }

    IntentionDisplay.value = false
}
const DemandDisplay = ref(false) //需求弹窗
const SingleChoiceRequirements = ref(null) //单选需求
const SelectRequirements = () => { // 选择需求
    DemandDisplay.value = true
    request({
        url: '/recruitmentBasics/findByStatus1',
        method: 'get',
        params: {}
    })
        .then(res => {
            console.log("需求数据", res.data);
            DemandData.value = res.data
        })
}

const DemandData = ref([//需求数据

]);
// 需求
const DemandHeader = ref([

    { id: "jobname", label: '职位名称', width: '160' },
    { id: "department.deptName", label: '部门', width: '160' },
    { id: "jobnature", label: '岗位性质', width: '160' },
    { id: "demandsubmitter", label: '提交人', width: '160' },
    { id: "numberofpositions", label: '需要人数', width: '160' },

])
const RequirementID = ref("选择需求")

const jobname = ref(null) //职位名称
// 需求确定
const DemandDetermination = () => {
    const selectedRow = DemandData.value.find(row => row.requirementid === SingleChoiceRequirements.value);
    if (selectedRow) {
        console.log('选中的数据:', selectedRow);
        RequirementID.value = selectedRow.requirementid;
        jobname.value = selectedRow.jobname;
    } else {

        ElMessage.error('未找到匹配的行');
    }

    DemandDisplay.value = false

}

const TheInterviewerShows = ref(false)// 面试官显示
const InterviewerName = ref("面试官选择") // 面试官选择
const interviewerId = ref([]) // 面试官id
const InterviewerButton = () => {  // 面试官按钮
    NumberOfInterviews.value = form.value.interviewRound
    if (NumberOfInterviews.value > 0) {
        request.get('/interviewer/find').then(res => {
            console.log("面试官数据", res.data);
            InterviewerData.value = res.data
            TheInterviewerShows.value = true
            
            // 清除之前的选择
            nextTick(() => {
                if (interviewerTableRef.value) {
                    interviewerTableRef.value.clearSelection();
                }
            });
        })
    } else {
        ElMessage.warning("请选择面试次数")
    }
}

// 面试官确定
const TheInterviewerIsConfirmed = () => {
    // 使用selection-change事件中维护的selectedInterviewers
    const selectedRows = selectedInterviewers.value;

    if (selectedRows && selectedRows.length > 0) {
        // 检查选择的面试官数量是否超过面试轮次
        const maxSelections = parseInt(form.value.interviewRound);
        if (selectedRows.length > maxSelections) {
            ElMessage.error(`最多只能选择${maxSelections}个面试官`);
            return;
        }

        console.log('选中的数据:', selectedRows);
        // 显示所有选中的面试官名称
        InterviewerName.value = selectedRows.map(row => row.employee.employeeName).join(', ');
        interviewerId.value = selectedRows.map(row => row.employee.employeeId);
        console.log("面试官id", interviewerId.value);

    } else {
        ElMessage.error('请选择至少一个面试官');
        return;
    }
    // 关闭弹窗
    TheInterviewerShows.value = false

}

const InterviewerInformation = ref([
    { id: 'employee.employeeName', label: '面试官名称', width: '100px' }
])
const InterviewerData = ref([
    interviewerId.value
])

const selectedInterviewers = ref([]) // 已选择的面试官

// 处理面试官选择变化
const handleSelectionChange = (selection) => {
    selectedInterviewers.value = selection;
    const maxSelections = parseInt(form.value.interviewRound) || 0;
    
    // 如果选择的数量超过了限制，自动取消多余的选择
    if (selection.length > maxSelections && interviewerTableRef.value) {
        // 保留前maxSelections个选择
        const rowsToSelect = selection.slice(0, maxSelections);
        
        // 清除所有选择
        interviewerTableRef.value.clearSelection();
        
        // 重新选择前maxSelections个
        nextTick(() => {
            rowsToSelect.forEach(row => {
                interviewerTableRef.value.toggleRowSelection(row, true);
            });
            
            if (maxSelections > 0) {
                ElMessage.warning(`面试轮次为${maxSelections}，最多只能选择${maxSelections}个面试官`);
            }
        });
    }
    
    // 更新面试时间安排数组
    updateInterviewSchedules(selection.length);
};

// 更新面试时间安排数组
const updateInterviewSchedules = (count) => {
    // 保持现有值，只调整数组长度
    const currentLength = interviewSchedules.value.length;
    if (count > currentLength) {
        // 增加空的时间安排项
        for (let i = currentLength; i < count; i++) {
            interviewSchedules.value.push({
                startTime: '',
                endTime: ''
            });
        }
    } else if (count < currentLength) {
        // 减少时间安排项
        interviewSchedules.value.splice(count);
    }
};

// 处理面试官对话框打开
const handleInterviewerDialogOpen = () => {
    nextTick(() => {
        if (interviewerTableRef.value) {
            interviewerTableRef.value.clearSelection();
        }
    });
};

const NumberOfInterviews = ref() //面试次数
// 面试次数
const InterviewRound = ref([{
    value: '1',
    label: '1'
}, {
    value: '2',
    label: '2'
}, {
    value: '3',
    label: '3'
}, {
    value: '4',
    label: '4'
}]);

// 当面试轮次发生变化时，检查已选择的面试官数量
watch(() => form.value.interviewRound, (newVal, oldVal) => {
    // 如果已经选择了面试官，并且新的面试轮次小于已选择的面试官数量，则清空选择
    if (TheInterviewerShows.value && selectedInterviewers.value.length > 0) {
        const maxSelections = parseInt(newVal) || 0;
        if (selectedInterviewers.value.length > maxSelections) {
            ElMessage.warning(`面试轮次已更改为${newVal}，请重新选择面试官`);
            // 清空已选择的面试官
            InterviewerName.value = "面试官选择";
            interviewerId.value = [];
            selectedInterviewers.value = [];
            
            // 清除表格选择
            if (interviewerTableRef.value) {
                interviewerTableRef.value.clearSelection();
            }
        }
    }
    
    // 更新面试时间安排数组
    updateInterviewSchedules(selectedInterviewers.value.length);
});

// 保存
const onSubmit = () => {
    console.log("13525", form);

    // 构造提交数据
    const submitData = {
        recruitmentDemandNumber: form.value.recruitmentDemandNumber,
        interviewRound: form.value.interviewRound,
        interviewSchedules: interviewSchedules.value,
        interviewerIds: interviewerId.value,
       interviewinterviewers: InterviewerData.value
    };
    console.log("提交数据", submitData);
    request({
        url: '/interviewschedule/insert',
        method: 'post',
        data: submitData
    }).then(res => {
        ElMessage.success('保存成功')
        emit('ref')
    }).catch(err => {
        ElMessage.error('保存失败')
    })
}
// 取消
const Cancel = () => {
    emit('ref')
}
</script>

<style scoped>
/* 外层容器，可控制整体条的高度、圆角等 */
.progress-bar {
    height: 6px;
    background-color: #ccebf7;
    border-radius: 3px;
    display: flex;
    width: 100%;
    /* 确保进度条容器宽度占满父容器 */
    overflow: hidden;
    /* 防止子元素溢出 */
}

.progress {
    width: 8%;
    height: 10;
    background-color: #61c3ea;
    border-radius: 3px 0 0 3px;
    transition: width 0.3s ease;
    /* 添加宽度变化的过渡效果 */
}

.form-footer {
    /* 将元素固定在浏览器视口的底部 */
    position: fixed;
    /* 元素距离底部 0 像素 */
    bottom: 0;
    /* 元素距离左侧 0 像素（占据整个水平方向） */
    left: 0;
    /* 元素宽度为视口的 100% */
    width: 100%;
    /* 设置白色背景色，防止内容穿透 */
    background-color: #ffffff;
    /* 设置 z-index 层级为 999，确保页脚始终显示在其他元素之上 */
    z-index: 999;
    /* 内边距为 10px*/
    padding: 10px;
    /* 添加阴影效果：水平偏移0，垂直偏移2px，模糊半径12px，颜色为半透明黑色 */
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 单选框选中样式 */
.el-radio.is-checked .radio-custom {
    background-color: #61c3ea;
    border-color: #409EFF;
}
</style>
